package zju.lzy.service.device;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zju.lzy.dto.Device;
import zju.lzy.mapper.DeviceMapper;
import zju.lzy.service.IOTProperties;
import zju.lzy.service.message.MessageReceiver;
import zju.lzy.service.message.MessageService;

import java.util.Deque;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * @author lzy
 * <p>
 * 管理device进程，处理重启后的对所有device的启动
 */
@Component
public class DeviceService {

    private static final Logger logger = LoggerFactory.getLogger(MessageService.class);

    /**
     * 只管理active的设备
     */
    Deque<WorkerThread> workers = new ConcurrentLinkedDeque<>();

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private MessageReceiver receiver;

    @Autowired
    IOTProperties properties;

    static int cur = 0;


    public boolean startDevice(Device device) {
        try {
            // 创建对应WorkerThread
            WorkerThread workerThread = new WorkerThread(device);
            workerThread.start();
            receiver.subscribeTopic(device.getTopic());
            // 加入管理队列
            workers.push(workerThread);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 停止device,直接将其从workerList中移除即可
     *
     * @param deviceId
     * @return 成功返回true，否则返回false
     */
    public boolean stopDevice(Integer deviceId) {
        for (WorkerThread workerThread : workers) {
            if (workerThread.getDeviceId() == deviceId) {
                workerThread.setRunning(false);
                return workers.remove(workerThread);
            }
        }
        return false;
    }


    public void restartDevices() {
        List<Device> devices = deviceMapper.getAllActiveDevices();
        for (Device device : devices) {
            if (device.isActive()) {
                startDevice(device);
            }
        }
        logger.info("程序初始化重启设备完成，当前活跃设备数量为：{}", devices.size());
    }

    /**
     * @param device
     * @return
     */
    private WorkerThread getWorkerByDevice(Device device) {
        for (WorkerThread workerThread : workers) {
            if (workerThread.getDeviceId() == device.getDeviceId()) {
                return workerThread;
            }
        }
        return null;
    }

    /**
     * 更改device的函数
     *
     * @param device
     * @return
     */
    public boolean alterDevice(Device device) {
        if (deviceMapper.alterDevice(device)) {
            WorkerThread workerThread = getWorkerByDevice(device);
            if (workerThread != null) {
                workerThread.setClientPrefix(device.getClientPrefix());
                workerThread.setInitLat(device.getInitLat());
                workerThread.setInitLon(device.getInitLon());
            }
            return true;
        }
        return false;
    }

}
